package com.bsoft.exchange.service;

import com.bsoft.exchange.dao.his.*;
import com.bsoft.exchange.dao.portal.HospitalInformationMapper;
import com.bsoft.exchange.domain.*;
import com.bsoft.exchange.param.DetailReport;
import com.bsoft.exchange.param.FeeSettlement;
import com.bsoft.exchange.pojo.*;
import com.bsoft.exchange.util.*;
import com.github.dozermapper.core.DozerBeanMapperBuilder;
import com.github.dozermapper.core.Mapper;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 创建日期 : 2019/6/12
 * 创建人 : 赵太行
 * 负责支付模块的服务
 */
@Service
public class PaymentService {

    private static final Logger logger = LoggerFactory.getLogger(PaymentService.class);

    @Autowired
    PaymentMapper paymentMapper;

    @Autowired
    MedicalSkillMapper medicalSkillMapper;

    @Autowired
    SystemConfigMapper systemConfigMapper;

    @Autowired
    PublicService publicService;

    @Autowired
    IdentityManager identityManager;

    @Autowired
    PatientMapper patientMapper;

    @Autowired
    RegisterMapper registerMapper;

    @Autowired
    CreateOrderNoMapper createOrderNoMapper;

    @Autowired
    CreateOrderNoService createOrderNoService;

    @Autowired
    HospitalInformationMapper hospitalInformationMapper;

    @Autowired
    YBService ybService;

    @Autowired
    AppointmentMapper appointmentMapper;

    @Autowired
    YBServiceMapper ybServiceMapper;

    private Mapper mapper = DozerBeanMapperBuilder.buildDefault();

    private List<String> brdaList;

    private double gbxj;
    private double hjje;

    private MergingDetails mergingDetails;
    private String yPname = "";

    public BaseResponse<List<UnPayedListDomain>> getUnPayedListService(UnPayedPojo unPayedPojo) throws SQLException {
        BaseResponse<List<UnPayedListDomain>> baseResponse = new BaseResponse<>();

        if (!unPayedPojo.getQueryType().equals(1)) {
            brdaList = publicService.getBRIDist(unPayedPojo.getOrganizationId(), unPayedPojo.getQueryType(), unPayedPojo.getPatientIdentityCardList(), unPayedPojo.getPatientMedicalCardNumberList());
        } else {
            brdaList = unPayedPojo.getPatientIdList();
        }
        if (brdaList == null) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("数据库查询失败,请检查参数设置");
            return baseResponse;
        }
        if (brdaList.size() == 0) {
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage("获取不到该病人信息");
            return baseResponse;
        }
        //获取病人ID对应的信息
        List<BrdaInfo> mzhmList = paymentMapper.getMzhmList(brdaList);
        //请求医生信息
        List<UnPayedListDomain> unPayedListDomainList = paymentMapper.getMedicalList(unPayedPojo.getOutpatientType(), unPayedPojo.getOrganizationId(), unPayedPojo.getBeginTime(), unPayedPojo.getEndTime(), brdaList, null);
        if (unPayedListDomainList.size() == 0) {
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage("暂无数据");
            return baseResponse;
        }
        for (UnPayedListDomain unPayedListDomain : unPayedListDomainList) {
            for (BrdaInfo brdaInfo : mzhmList) {
                if (brdaInfo.getBRID().equals(unPayedListDomain.getPatientId())) {
                    unPayedListDomain.setPatientMedicalCardNumber(brdaInfo.getMZHM());
                }
            }
        }
        //将是中药的处方进行合并，并且计算金额
        for (int t = 0; t < unPayedListDomainList.size(); t++) {
            List<MedicalInformation> medicalList = unPayedListDomainList.get(t).getMedicalInformation();
            for (int i = 0; i < medicalList.size(); i++) {
                MedicalInformation medicalInformation = medicalList.get(i);
                for (int j = 0; j < medicalInformation.getMergingItems().size(); j++) {

                    MergingItem mergingItem = medicalInformation.getMergingItems().get(j);
                    for (int y = 0; y < mergingItem.getDetailsItems().size(); y++) {
                        MergingDetails mergingDetails = mergingItem.getDetailsItems().get(y);
                        gbxj = SumPriceUtil.getAddPriceDouble(gbxj, mergingDetails.getFee());
                    }
                    //}
                    medicalList.get(i).getMergingItems().get(j).setMergingSubtotal(gbxj);
                    hjje = SumPriceUtil.getAddPriceDouble(gbxj, hjje);
                    gbxj = 0;
                    yPname = null;
                    mergingDetails = null;
                }
                medicalList.get(i).setTotalFee(hjje);
                hjje = 0;
            }
        }
        baseResponse.setCode(Constant.successTag);
        baseResponse.setData(unPayedListDomainList);
        yPname = null;
        mergingDetails = null;
        return baseResponse;
    }

    public BaseResponse<DrugDomain> getUnPayedListServiceExt(UnPayedPojo unPayedPojo) throws SQLException {
        logger.info("========= unPayedPojo : {} ==========",unPayedPojo);
        BaseResponse<DrugDomain> baseResponse = new BaseResponse<>();
        brdaList = unPayedPojo.getPatientIdList();
        if (brdaList == null) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("数据库查询失败,请检查参数设置");
            return baseResponse;
        }
        if (brdaList.size() == 0) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("获取不到该病人信息");
            return baseResponse;
        }
        //获取病人ID对应的信息
        List<BrdaInfo> mzhmList = paymentMapper.getMzhmList(brdaList);
        //请求医生信息
        List<Long> orderIds = new ArrayList<>();
        orderIds.add(unPayedPojo.getOrderId());
        UnPayedListDomain unPayedListDomain = paymentMapper.getMedicalListExt(unPayedPojo.getOutpatientType(), unPayedPojo.getOrganizationId(), unPayedPojo.getBeginTime(), unPayedPojo.getEndTime(), brdaList, orderIds);
        if (unPayedListDomain == null) {
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage("暂无数据");
            return baseResponse;
        }
            for (BrdaInfo brdaInfo : mzhmList) {
                if (brdaInfo.getBRID().equals(unPayedListDomain.getPatientId())) {
                    unPayedListDomain.setPatientMedicalCardNumber(brdaInfo.getMZHM());
                }
            }
        //将是中药的处方进行合并，并且计算金额
            List<MedicalInformation> medicalList = unPayedListDomain.getMedicalInformation();
            for (int i = 0; i < medicalList.size(); i++) {
                MedicalInformation medicalInformation = medicalList.get(i);
                for (int j = 0; j < medicalInformation.getMergingItems().size(); j++) {

                    MergingItem mergingItem = medicalInformation.getMergingItems().get(j);
                    for (int y = 0; y < mergingItem.getDetailsItems().size(); y++) {
                        MergingDetails mergingDetails = mergingItem.getDetailsItems().get(y);
                        gbxj = SumPriceUtil.getAddPriceDouble(gbxj, mergingDetails.getFee());
                    }
                    //}
                    medicalList.get(i).getMergingItems().get(j).setMergingSubtotal(gbxj);
                    hjje = SumPriceUtil.getAddPriceDouble(gbxj, hjje);
                    gbxj = 0;
                    yPname = null;
                    mergingDetails = null;
                }
                medicalList.get(i).setTotalFee(hjje);
                hjje = 0;
            }
        List<MedicalInformation> medicalInformations = unPayedListDomain.getMedicalInformation();
        MedicalInformation medicalInformation = medicalInformations.get(0);
        DrugDomain drugDomain = new DrugDomain();
        // 1 已支付 ，2 已撤销, 0 未支付
        for (MedicalInformation u : unPayedListDomain.getMedicalInformation()) {
            u.getMergingItems().forEach(u1 -> {
                if (StringUtils.isNotBlank(u1.getFphm()) && u1.getZfpb() == 0) {
                    u1.setPayStatus(1);
                } else if(u1.getZfpb() == 1){
                    u1.setPayStatus(2);
                } else {
                    u1.setPayStatus(0);
                }


            });
        }
        drugDomain.setTotal(medicalInformation.getTotalFee());
        drugDomain.setCreateTime(medicalInformation.getMedicalDate());
        List<MergingItem> mergingItems = medicalInformation.getMergingItems();
        mergingItems.forEach(m -> {
            drugDomain.setPrescriptionCode(m.getFeeNo());
            drugDomain.setPayStatus(m.getPayStatus());
            List<MergingDetails> detailsItems = m.getDetailsItems();
            List<DrugDomain.Item> collect = detailsItems.stream().map(d -> {
                DrugDomain.Item item = new DrugDomain.Item();
                item.setName(d.getItemName());
                item.setDrugUsage(d.getDrugUsage());
                item.setFrequency(d.getFrequency());
                item.setNumber(Integer.valueOf(d.getItemNumber()));
                item.setPrice(d.getPrice());
                item.setSpecifications(d.getSpecifications());
                return item;
            }).collect(Collectors.toList());
            drugDomain.setDrugList(collect);
        });
        baseResponse.setCode(Constant.successTag);
        baseResponse.setData(drugDomain);
        yPname = null;
        mergingDetails = null;
        return baseResponse;
    }

    public BaseResponse<List<MS_YJ02Domain>> getMachiningChineseHerbalMedicineCost(FeeNoPojo feeNoPojo) {
        BaseResponse<List<MS_YJ02Domain>> baseResponse = new BaseResponse<>();
        Long jgid;
        Long yjxh;

        String feeNo;

        List<MS_YJ02Domain> MS_YJ02List = new ArrayList();
        jgid = Long.parseLong(feeNoPojo.getOrganizationId());
        feeNo = feeNoPojo.getFeeNo();
        if (feeNo == null || "".equals(feeNo)) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("单据识别序号不能为空!");

            return baseResponse;
        }
//        String[] mzxhList;
//        feeNo = feeNo.replace("，", ",");
//        mzxhList = feeNo.split(",");  
//		
//		Map<String, Object> mzxhParam = new HashMap<String, Object>();
//		mzxhParam.put("jgid", jgid);
//		mzxhParam.put("mzxhList", mzxhList);
//		MS_YJ02List = medicalSkillMapper.getDetailByMZXHList(mzxhParam);

        String[] yjxhList;
        feeNo = feeNo.replace("，", ",");
        yjxhList = feeNo.split(",");

        Map<String, Object> yjxhParam = new HashMap<String, Object>();
        yjxhParam.put("jgid", jgid);
        yjxhParam.put("yjxhList", yjxhList);
        MS_YJ02List = medicalSkillMapper.getDetailByYJXHList(yjxhParam);

        if (MS_YJ02List == null || MS_YJ02List.size() < 1) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("未查询到该单据识别序号的数据!");

            return baseResponse;
        }
        baseResponse.setCode(Constant.successTag);
        baseResponse.setData(MS_YJ02List);

        return baseResponse;
    }

    public BaseResponse<FeeVoDomain> getFeeDetail(InvoiceNumberPojo invoiceNumberPojo) {
        BaseResponse<FeeVoDomain> baseResponse = new BaseResponse<>();

        Map<String, Object> ret = new HashMap<String, Object>();

        Long brid;
        String fphm;

        if (invoiceNumberPojo.getOrganizationId() == null || "".equals(invoiceNumberPojo.getOrganizationId())) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("医院识别代码不能为空!");

            return baseResponse;
        }

        List<HospitalInformation> hospitalInformationList = hospitalInformationMapper.selectList(invoiceNumberPojo.getOrganizationId());
        fphm = invoiceNumberPojo.getInvoiceNumber();
        if (fphm == null || "".equals(fphm)) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("发票号码不能为空!");

            return baseResponse;
        }
        if (invoiceNumberPojo.getPatientId() == null) {
            brid = (long) 0;
        } else {
            brid = Long.parseLong(invoiceNumberPojo.getPatientId());
        }

        List<FeeAllDomain> feeAllList = paymentMapper.getFeeDetail(Long.valueOf(invoiceNumberPojo.getOrganizationId()), brid, fphm);

        if (feeAllList == null || feeAllList.size() < 1) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("未查询到该发票号码的数据!");

            return baseResponse;
        }
        FeeRecordDomain feeRecord = new FeeRecordDomain();

        List<FeeRecordDomain> feeRecordList = new ArrayList();
        List<FeeDetailDomain> feeFeeDetailList = new ArrayList();

        Long feeNo = (long) 0;
        Integer feeTypeCode = 0;
        Long groupNo = (long) 0;
        Double totalFee = 0.00;
        Long feeNoNew;
        Integer feeTypeCodeNew;
        Long groupNoNew;
        Long i = (long) 0;
        Double payAmount = 0.00;
        Double totalFeeAll = 0.00;

        FeeVoDomain feeVoDomain = new FeeVoDomain();
        for (FeeAllDomain feeAll : feeAllList) {
            feeNoNew = feeAll.getFeeNo();
            feeTypeCodeNew = feeAll.getFeeTypeCode();
            groupNoNew = feeAll.getGroupNo();
            feeVoDomain.setUrl(feeAll.getUrl());

            if (!feeNo.equals(feeNoNew) || !feeTypeCode.equals(feeTypeCodeNew) || !groupNo.equals(groupNoNew)) {

                //FeeRecordDomain feeRecord = new FeeRecordDomain();
                if (i > 0) {
                    feeRecordList.add(feeRecord);
                }
                i++;
                feeRecord = new FeeRecordDomain();
//                feeRecord.setUrl(feeAll.getUrl());
//          		 feeRecord.setFeeNo(feeNo.toString());
//          		 feeRecord.setFeeTypeCode(feeTypeCode.toString());
                feeRecord.setFeeNo(feeAll.getFeeNo().toString());
                feeRecord.setFeeTypeCode(feeAll.getFeeTypeCode().toString());
                feeRecord.setFeeTypeName(feeAll.getFeeTypeName());

			 /*feeRecord.setDepartmentId(feeAll.getDepartmentCode());
			 feeRecord.setDepartmentName(feeAll.getDepartmentName());*/

                //第一次获取基本信息
                if ("1".equals(i.toString())) {

                    feeVoDomain.setDepartmentId(feeAll.getDepartmentCode());
                    feeVoDomain.setDepartmentName(feeAll.getDepartmentName());
                    feeVoDomain.setDoctorName(feeAll.getDoctorName());
                    feeVoDomain.setDoctorId(feeAll.getDoctorCode());
                    feeVoDomain.setMedicalDate(feeAll.getMedicalDate());
                    feeVoDomain.setPatientMedicalCardType(feeAll.getPatientMedicalCardType());
                    feeVoDomain.setPatientMedicalCardNumber(feeAll.getPatientMedicalCardNumber());
                    feeVoDomain.setPatientId(feeAll.getPatientId());
                    feeVoDomain.setPatientName(feeAll.getPatientName());
                    feeVoDomain.setPatientNature(feeAll.getPatientNature());
                    feeVoDomain.setPrintStatus(feeAll.getPrintStatus());
                    feeVoDomain.setPayTime(feeAll.getPayTime());
                }

                //feeRecord.setDetails(details);
			 /*feeRecord.setDoctorId(feeAll.getDoctorCode());
			 feeRecord.setDoctorName(feeAll.getDoctorName());*/
                feeRecord.setFeeDate(feeAll.getFeeDate());
			/* feeRecord.setPatientName(feeAll.getPatientName());
			 feeRecord.setPayStatus(feeAll.getPayStatus());*/

                feeFeeDetailList = new ArrayList();
                totalFee = 0.00;
            }
            FeeDetailDomain feeDetail = new FeeDetailDomain();
            feeDetail.setDays(feeAll.getDays());
            feeDetail.setDecoctionDesc(feeAll.getDecoctionDesc());
            feeDetail.setDosage(feeAll.getDosage());
            feeDetail.setDosageUnit(feeAll.getDosageUnit());
            feeDetail.setFrequency(feeAll.getFrequency());
            feeDetail.setFrequencyCode(feeAll.getFrequencyCode());
            feeDetail.setGroupNo(groupNo.toString());
            feeDetail.setItemCode(feeAll.getItemCode());
            feeDetail.setItemName(feeAll.getItemName());
            feeDetail.setItemNumber(feeAll.getItemNumber());
            feeDetail.setPrice(feeAll.getPrice());
            feeDetail.setRemark(feeAll.getRemark());
            feeDetail.setSpecification(feeAll.getSpecification());
            feeDetail.setFee(feeAll.getTotalFee());
            feeDetail.setUsage(feeAll.getUsage());
            feeDetail.setUsageCode(feeAll.getUsageCode());
            totalFee = SumPriceUtil.getAddPriceDouble(totalFee, feeDetail.getFee());
            feeFeeDetailList.add(feeDetail);
            feeRecord.setDetails(feeFeeDetailList);
            feeRecord.setAmount(totalFee);
            totalFeeAll = SumPriceUtil.getAddPriceDouble(totalFeeAll, totalFee);
            payAmount = SumPriceUtil.getAddPriceDouble(payAmount, feeAll.getPayAmount());

            feeNo = feeNoNew;
            feeTypeCode = feeTypeCodeNew;
            groupNo = groupNoNew;

        }

        feeRecordList.add(feeRecord);

        feeVoDomain.setRecord(feeRecordList);
        feeVoDomain.setTotalFee(totalFeeAll);
        feeVoDomain.setPayAmount(payAmount);
        for (HospitalInformation yymc : hospitalInformationList) {
            if (invoiceNumberPojo.getOrganizationId().equals(yymc)) {
                feeVoDomain.setOrganizationName(yymc.getOrganizationName());
            }
        }

        feeVoDomain.setInvoiceNumber(invoiceNumberPojo.getInvoiceNumber());
        //业务类别：1，挂号，2 诊间支付，3预缴金充值，4住院结算
        GY_SHDDHDomain shddh = createOrderNoMapper.getShddhByFphm(invoiceNumberPojo.getInvoiceNumber(), Long.valueOf(invoiceNumberPojo.getOrganizationId()), 2);
        if (shddh != null) {
            feeVoDomain.setAgtOrderNumber(shddh.getJylsh());
            feeVoDomain.setPayMode(shddh.getZffs().toString());
        }
        //ret.put("record", feeRecordList);

        baseResponse.setCode(Constant.successTag);
        baseResponse.setData(feeVoDomain);

        return baseResponse;

    }

    public BaseResponse<List<PaymentDomain>> getPatmentList(PaymentPojo paymentPojo) throws SQLException {
        BaseResponse<List<PaymentDomain>> baseResponse = new BaseResponse<>();

        if (!paymentPojo.getQueryType().equals(1)) {
            brdaList = publicService.getBRIDist(paymentPojo.getOrganizationId(),
                    paymentPojo.getQueryType(), paymentPojo.getPatientIdentityCardList(), paymentPojo.getPatientMedicalCardList());
        } else {
            brdaList = paymentPojo.getPatientIdList();
        }
        if (brdaList == null) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("数据库查询失败,请检查参数设置");
            return baseResponse;
        }
        if (brdaList.size() == 0) {
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage("获取不到该病人信息");
            return baseResponse;
        }
        List<PaymentDomain> paymentDomainList = paymentMapper.getPayList(paymentPojo.getExecuteFlag(), paymentPojo.getOutpatientType(), paymentPojo.getOrganizationId(), paymentPojo.getBeginTime(), paymentPojo.getEndTime(), brdaList);
        if (paymentDomainList.size() == 0) {
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage("暂无数据");
            return baseResponse;
        }
        baseResponse.setCode(Constant.successTag);
        baseResponse.setData(paymentDomainList);
        return baseResponse;
    }

    /**
     * 根据病人标识获取费用预结算信息
     */
    public BaseResponse<GetPrecalculatedFee> getPrecalculatedFee(GetPrecalculatedFeePojo getPrecalculatedFeePojo, Integer type, boolean flag) {
//        flag = false;
        Gson gson = new Gson();
        logger.info("========= getPrecalculatedFeePojo 预结算入参:{} ==========", gson.toJson(getPrecalculatedFeePojo));
        List<DetailReportResponse> detailReportResponses = new ArrayList<>();
        GetPrecalculatedFee precalculatedFee = new GetPrecalculatedFee();
        List<GetPrecalculatedFeeData> list = new ArrayList<>();// 费用信息
        BaseResponse<GetPrecalculatedFee> baseResponse = new BaseResponse<>();
        String mzlsh = "";
        String ybkh = "";
        try {


            String hospitalCode = "1";
            String patientCode = getPrecalculatedFeePojo.getPatientId();
            if (hospitalCode == null || "".equals(hospitalCode)) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("医院代码不能为空!");

                return baseResponse;
            }
            Long jgid = Long.parseLong(hospitalCode);
            if (patientCode == null || "".equals(patientCode)) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("病人标识不能为空!");

                return baseResponse;
            }
            baseResponse.setCode(Constant.successTag);
            baseResponse.setMessage("处理成功");
//			预结算逻辑：
//			根据入参feeNo，feeTypeCode得到cfsb,yjxh
//			feeTypeCode:1,西药，2中药，3草药0，医技，到时需统一
            List<String> cfsbList = new ArrayList<>();  //处方列表
            List<String> yjxhList = new ArrayList<>();  //医技列表

            //获取单据列表 包含处方 医技
            List<BillDataPojo> feeRecords = getPrecalculatedFeePojo.getFeeRecords();
            for (BillDataPojo feeRecord : feeRecords) {
                //feeTypeCode:1,西药，2中药，3草药
                if ("1".equals(feeRecord.getFeeTypeCode()) || "2".equals(feeRecord.getFeeTypeCode()) || "3".equals(feeRecord.getFeeTypeCode())) {
                    cfsbList.add(feeRecord.getFeeNo());
                } else {
                    yjxhList.add(feeRecord.getFeeNo());
                }
            }

            //判断是否有已收费
            List<GetPrecalculatedFeeCheckData> checkList = new ArrayList<>();
            checkList = paymentMapper.getPrecalculatedFeeCheckData(hospitalCode, cfsbList, yjxhList);
            for (GetPrecalculatedFeeCheckData check : checkList) {
                if (check.getFphm() != null && !"".equals(check.getFphm())) {
                    baseResponse.setCode(Constant.breakTag);
                    baseResponse.setMessage("单据【" + check.getFeeNo() + "】已经收过费，不能重复收费!");

                    return baseResponse;
                }

                if (check.getMzxh() != null && check.getMzxh() > 0) {
                    baseResponse.setCode(Constant.breakTag);
                    baseResponse.setMessage("单据【" + check.getFeeNo() + "】已经收过费，不能重复收费!");

                    return baseResponse;
                }

                if (check.getTybz() != null && check.getTybz() > 0) {
                    baseResponse.setCode(Constant.breakTag);
                    baseResponse.setMessage("单据【" + check.getFeeNo() + "】已经退药，不能进行收费!");

                    return baseResponse;
                }

                if (check.getZfpb() != null && check.getZfpb() > 0) {
                    baseResponse.setCode(Constant.breakTag);
                    baseResponse.setMessage("单据【" + check.getFeeNo() + "】已经作废，不能进行收费!");

                    return baseResponse;
                }

            }

            int xswws = Integer.parseInt(systemConfigMapper.getValueByConfigName(jgid, "GY_MZZYJEXSWS"));
            list = paymentMapper.getPrecalculatedFee(hospitalCode, cfsbList, yjxhList);
            double amount = 0.00;
            double zfje = 0.00;
//			List<GetPrecalculatedFeeData2> feeDataList = new ArrayList<>();

            if (list.size() > 0) {
                for (GetPrecalculatedFeeData precalculatedFeeData : list) {
                    amount += precalculatedFeeData.getMergingSubtotal();
                    zfje += precalculatedFeeData.getZfje();
//					
//					GetPrecalculatedFeeData2 feeData = new GetPrecalculatedFeeData2();
//					feeData.setMergingCode(precalculatedFeeData.getMergingCode());
//					feeData.setMergingName(precalculatedFeeData.getMergingName());
//					feeData.setMergingSubtotal(precalculatedFeeData.getMergingSubtotal());
//					
//					feeDataList.add(feeData);

                }
                //precalculatedFee.setAmount(new BigDecimal(String.valueOf(zfje)).setScale(xswws,BigDecimal.ROUND_HALF_UP).doubleValue());
                precalculatedFee.setPayAmount(new BigDecimal(String.valueOf(amount)).setScale(xswws, BigDecimal.ROUND_HALF_UP).doubleValue());
                precalculatedFee.setTotalFee(new BigDecimal(String.valueOf(amount)).setScale(xswws, BigDecimal.ROUND_HALF_UP).doubleValue());
                precalculatedFee.setMergingItems(list);
//				precalculatedFee.setMergingItems(feeDataList);

                String outOrderNumber = "";

                //外部预结算调用才需要生成商户订单号
                if (type == 0) {

                    try {
                        //获取商户订单号  	业务类别：1，挂号，2 诊间支付，3预缴金充值，4住院结算
                        int zffs = 0;
                        BaseResponse<String> orderResponse = createOrderNoService.createShddh(jgid.intValue(), 2, zffs, amount, Integer.parseInt(patientCode));

                        if (orderResponse.getCode() != Constant.successTag) {
                            baseResponse.setCode(orderResponse.getCode());
                            baseResponse.setMessage(orderResponse.getMessage());

                            return baseResponse;
                        }

                        outOrderNumber = orderResponse.getData();

                    } catch (Exception e) {
                        e.printStackTrace();
                        baseResponse.setCode(Constant.errorTag);
                        baseResponse.setMessage("获取预结算标识(商户订单号)失败!");

                        return baseResponse;
                    }

                    precalculatedFee.setPaymentBudgetNumber(outOrderNumber);
                }

                baseResponse.setData(precalculatedFee);
                baseResponse.setCode(Constant.successResponse);
            } else {
                baseResponse.setMessage("未查询到数据");
                baseResponse.setData(null);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("处理失败");
        }

        return baseResponse;
    }

    /**
     * 互联网医院支付成功后，调用该接口通知HIS进行结算
     *
     * @param notifyPayedPojo
     * @return
     */

    public BaseResponse<NotifyPayed> notifyPayed(NotifyPayedPojo notifyPayedPojo, List<UnPayedListDomain> unPayedListDomains) {
        logger.info("============ 回调结算:{} ========", unPayedListDomains);
        BaseResponse<NotifyPayed> baseResponse = new BaseResponse<>();
        NotifyPayed notifyPayed = new NotifyPayed();

        baseResponse.setData(null);

        baseResponse = notifyPayedOrder(notifyPayedPojo);
        if (baseResponse.getCode() == Constant.errorTag) {
            return baseResponse;
        }
        baseResponse = notifyPayedHis(notifyPayedPojo, unPayedListDomains);
        if (baseResponse.getCode() == Constant.errorTag) {
            return baseResponse;
        }
        return baseResponse;
    }

    public BaseResponse<NotifyPayed> jktNotifyPayed(NotifyPayedPojo notifyPayedPojo) {
        logger.info("============ 回调结算:{} ========", notifyPayedPojo);
        BaseResponse<NotifyPayed> baseResponse = new BaseResponse<>();

        baseResponse.setData(null);

        baseResponse = notifyPayedOrder(notifyPayedPojo);
        if (baseResponse.getCode() == Constant.errorTag) {
            return baseResponse;
        }
        baseResponse = jktNotifyPayedHis(notifyPayedPojo);
        if (baseResponse.getCode() == Constant.errorTag) {
            return baseResponse;
        }
        return baseResponse;
    }

    @Transactional(value = "hisTransactionManager", rollbackFor = Exception.class)
    public BaseResponse<NotifyPayed> notifyPayedOrder(NotifyPayedPojo notifyPayedPojo) {
        BaseResponse<NotifyPayed> baseResponse = new BaseResponse<>();

        /*try {*/

        Long jgid;
        if (notifyPayedPojo.getOrganizationId() == null || "".equals(notifyPayedPojo.getOrganizationId())) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("医院代码不能为空!");
            return baseResponse;
        }
        jgid = 1L;

        Long brid;

        String patientCode = notifyPayedPojo.getPatientId();
        if (patientCode == null || "".equals(patientCode)) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("病人标识不能为空!");
            return baseResponse;
        }
        brid = Long.parseLong(patientCode);
			
			/*if (notifyPayedPojo.getOutOrderNumber() == null || "".equals(notifyPayedPojo.getOutOrderNumber())) {
				baseResponse.setCode(Constant.errorTag);
				baseResponse.setMessage("商户订单号不能为空!");
				return baseResponse;
			}*/

        if (notifyPayedPojo.getPaymentBudgetNumber() == null || "".equals(notifyPayedPojo.getPaymentBudgetNumber())) {
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("预结算标识不能为空!");
            return baseResponse;
        }

//			Long shddh;
//			shddh = Long.parseLong(notifyPayedPojo.getOutOrderNumber());

        createOrderNoMapper.updateShddhYwzt(notifyPayedPojo.getPaymentBudgetNumber(), 1, jgid.intValue());

		/*} catch (Exception e) {
			e.printStackTrace();
			baseResponse.setCode(Constant.errorTag);
			baseResponse.setMessage("更新商户订单号支付状态失败");
		}*/
        baseResponse.setCode(Constant.successTag);
        return baseResponse;
    }

    @Transactional(value = "hisTransactionManager", rollbackFor = Exception.class)
    public BaseResponse<NotifyPayed> jktNotifyPayedHis(NotifyPayedPojo notifyPayedPojo){
        logger.info("========= notifyPayedPojo:{} ==========",notifyPayedPojo);
        BaseResponse<NotifyPayed> baseResponse = new BaseResponse<>();
        NotifyPayed notifyPayed = new NotifyPayed();
        String ybkh = "";
        String mzlsh = "";
        baseResponse.setData(null);
        FeeSettlement feeSettlement = null;
        try {
            Long jgid;
            if (notifyPayedPojo.getOrganizationId() == null || "".equals(notifyPayedPojo.getOrganizationId())) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("医院代码不能为空!");
                return baseResponse;
            }
            jgid = 1L;

            Long brid;

            String patientCode = notifyPayedPojo.getPatientId();
            if (patientCode == null || "".equals(patientCode)) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("病人标识不能为空!");
                return baseResponse;
            }
            brid = Long.parseLong(patientCode);

			/*if (notifyPayedPojo.getOutOrderNumber() == null || "".equals(notifyPayedPojo.getOutOrderNumber())) {
				baseResponse.setCode(Constant.errorTag);
				baseResponse.setMessage("商户订单号不能为空!");
				return baseResponse;
			}*/
            if (notifyPayedPojo.getPaymentBudgetNumber() == null || "".equals(notifyPayedPojo.getPaymentBudgetNumber())) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("预结算标识不能为空!");
                return baseResponse;
            }
            if (StringUtils.isBlank(notifyPayedPojo.getAddress())){
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("药品配送地址不能为空!");
                return baseResponse;
            }

//			Long shddh;
//			shddh = Long.parseLong(notifyPayedPojo.getOutOrderNumber());
            Long mzxh = identityManager.getMax("MS_MZXX", 1);

            Date now = new Date();

            List<BillDataPojo> billList = notifyPayedPojo.getFeeRecords();
            Long jzxh = null;

            List<String> cfsbList = new ArrayList<>();  //处方列表
            List<String> yjxhList = new ArrayList<>();  //医技列表

            //获取单据列表 包含处方 医技
            for (BillDataPojo feeRecord : billList) {
                cfsbList.add(feeRecord.getFeeNo());
                //feeTypeCode:1,西药，2中药，3草药
                    if (jzxh == null || jzxh < 1) {
                        jzxh = paymentMapper.getJzxhCF(Long.parseLong(feeRecord.getFeeNo()));
                    }
            }

            GetPrecalculatedFeePojo getPrecalculatedFeePojo = new GetPrecalculatedFeePojo();

            getPrecalculatedFeePojo.setOrganizationId(notifyPayedPojo.getOrganizationId());
            getPrecalculatedFeePojo.setPatientId(notifyPayedPojo.getPatientId());
            getPrecalculatedFeePojo.setFeeRecords(notifyPayedPojo.getFeeRecords());

//			2、获取发票号码等信息：

            String fphm = systemConfigMapper.getValueByConfigName(1L, "WX_FPHM");
            Long wx_fphm = Long.parseLong(fphm) + 1;
            systemConfigMapper.updateValueByConfigName(1L, "WX_FPHM", wx_fphm.toString());


//			4、读取帐户信息帐户
            PatientDomain patient = patientMapper.getPatientById(brid);

//			5、写门诊信息ms_mzxx
            MS_MZXXDomain mzxx = new MS_MZXXDomain();

            mzxx.setBrid(brid);
            mzxx.setFphm(fphm);
            mzxx.setJgid(jgid);
            mzxx.setMzxh(mzxh);
            mzxx.setSfrq(now);
            mzxx.setBrxm(patient.getBrxm());
            mzxx.setBrxb(patient.getBrxb());
            mzxx.setBrxz(1000L);
            mzxx.setFyzh(patient.getFyzh());
            mzxx.setDwxh(patient.getDwxh());
            mzxx.setJzrq(null);
            mzxx.setCzgh("900002");
            mzxx.setZfpb(0);
            mzxx.setThpb(0);
            mzxx.setHbbz(0);

            mzxx.setZjje(notifyPayedPojo.getTotalFee());
            mzxx.setZfje(notifyPayedPojo.getPayAmount());
            //0：真实发票 1：门诊虚拟发票 2：药房虚拟发票 3：医技虚拟发票 4：诊间结算 5：自助结算，此处建议新增6：掌上医院
            mzxx.setSffs(0);

            mzxx.setQtys(notifyPayedPojo.getTotalFee() - notifyPayedPojo.getPayAmount());

            RegisterDomain register = registerMapper.getRegisterByJzxh(jgid, jzxh);
            mzxx.setMzlb(register.getMzlb());
            mzxx.setGhgl(register.getSbxh());
            mzxx.setApplx(8L);
            //交易流水号
            mzxx.setAppzfdjh(notifyPayedPojo.getAgtOrderNumber());
            mzxx.setFphm(fphm);
            mzxx.setAppzfje(notifyPayedPojo.getPayAmount());
            mzxx.setAppzffs("1");
            paymentMapper.saveMZXX(mzxx);

//			3、插入ms_sfmx表
//			将取预结算中归并的费用集合sfxm中的sfxm/zjje/zfje，另外补充字段数据jgid，fphm，mzxh
            List<GetPrecalculatedFeeData> precalculatedFeeList = paymentMapper.getPrecalculatedFee("1", cfsbList, yjxhList);
            for (GetPrecalculatedFeeData precalculatedFeeData : precalculatedFeeList) {
                MS_SFMXDomain sfmx = new MS_SFMXDomain();
                sfmx.setFphm(fphm);
                sfmx.setJgid(jgid);
                sfmx.setMzxh(mzxh);
                sfmx.setSfxm(precalculatedFeeData.getMergingCode().longValue());
                sfmx.setZfje(precalculatedFeeData.getMergingSubtotal());
                sfmx.setZjje(precalculatedFeeData.getMergingSubtotal());
                paymentMapper.saveSFMX(sfmx);
            }

//			6、写ms_cf01、ms_yj01相关数据

            paymentMapper.updateCFExt(Long.parseLong(fphm), mzxh, jgid, cfsbList,notifyPayedPojo.getAddress());
//            paymentMapper.updateYJ(Long.parseLong(fphm), mzxh, jgid, cfsbList, yjxhList);

//			7、写付款信息
//			如果zfje>0,则新增记录insert ms_fkxx:
            Long jlxh;
            Long fkfs = null;
            Long fklb = null;
            Long brxz = null;

            if (notifyPayedPojo.getPayAmount() > 0) {
                MS_FKXXDomain fkxx = new MS_FKXXDomain();
                jlxh = identityManager.getMax("MS_FKXX", 1);
                fkxx.setJlxh(jlxh);
                fkxx.setFkfs(notifyPayedPojo.getPayMode().longValue());
                fkxx.setFkhm(notifyPayedPojo.getChannelOrderNumber());
                fkxx.setFkje(notifyPayedPojo.getPayAmount());
                fkxx.setJgid(jgid);
                fkxx.setMzxh(mzxh);
                fkxx.setAppfkfs("1");
                paymentMapper.saveFKXX(fkxx);
            }

            int zffs = 0;
            BaseResponse<String> orderResponse = createOrderNoService.createShddh(jgid.intValue(), 2, zffs, notifyPayedPojo.getPayAmount(), Integer.parseInt(patientCode));

            //createOrderNoMapper.updateShddhYwzt(notifyPayedPojo.getOutOrderNumber(), 1, jgid.intValue());
            createOrderNoMapper.updateShddhZfzt(orderResponse.getData(), 1, new Date(), notifyPayedPojo.getPayMode(),
                    jgid.intValue(), notifyPayedPojo.getAgtOrderNumber(), fphm);

//			如果dzje>0,则新增记录insert ms_fkxx:
//			Fkfs = #
//			其他字段同上
//			其中：获取打折对应的付款方式，付款类别为5的是打折优惠
//			SELECT FKFS  From GY_FKFS Where (JGID = # or JGID = 0 ) and
//				FKLB = 5 And SYLX = 1
//
//			9、结算成功，返回数据。
            //notifyPayed.setTradeNo(mzxh.toString());
            notifyPayed.setResultId(mzxh.toString());
            notifyPayed.setInvoiceNumber(fphm.toString());
            notifyPayed.setAgtOrderNumber(notifyPayedPojo.getAgtOrderNumber());
            notifyPayed.setPaymentBudgetNumber(notifyPayedPojo.getPaymentBudgetNumber());

            List<NotifyPayedData> notifyPayedData = paymentMapper.getNotifyPayedData(jgid.toString(), cfsbList, yjxhList);
            ;

            notifyPayed.setFeeRecords(notifyPayedData);

//			baseResponse.setCode(Constant.successTag);
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage(notifyPayedPojo.getNotify());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();
            baseResponse.setCode(Constant.errorTag);
            baseResponse.setMessage("处理失败");
        }

        baseResponse.setData(notifyPayed);

        return baseResponse;
    }

    /**
     * 互联网医院支付成功后，调用该接口通知HIS进行结算
     *
     * @param notifyPayedPojo
     * @return
     */
    @Transactional(value = "hisTransactionManager", rollbackFor = Exception.class)
    public BaseResponse<NotifyPayed> notifyPayedHis(NotifyPayedPojo notifyPayedPojo, List<UnPayedListDomain> unPayedListDomains) {
        logger.info("========= notifyPayedPojo:{} ==========",notifyPayedPojo);
        BaseResponse<NotifyPayed> baseResponse = new BaseResponse<>();
        NotifyPayed notifyPayed = new NotifyPayed();
        String ybkh = "";
        String mzlsh = "";
        baseResponse.setData(null);
        FeeSettlement feeSettlement = null;
        try {
            Long jgid;
            if (notifyPayedPojo.getOrganizationId() == null || "".equals(notifyPayedPojo.getOrganizationId())) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("医院代码不能为空!");
                return baseResponse;
            }
            jgid = 1L;

            Long brid;

            String patientCode = notifyPayedPojo.getPatientId();
            if (patientCode == null || "".equals(patientCode)) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("病人标识不能为空!");
                return baseResponse;
            }
            brid = Long.parseLong(patientCode);
			
			/*if (notifyPayedPojo.getOutOrderNumber() == null || "".equals(notifyPayedPojo.getOutOrderNumber())) {
				baseResponse.setCode(Constant.errorTag);
				baseResponse.setMessage("商户订单号不能为空!");
				return baseResponse;
			}*/
            if (notifyPayedPojo.getPaymentBudgetNumber() == null || "".equals(notifyPayedPojo.getPaymentBudgetNumber())) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("预结算标识不能为空!");
                return baseResponse;
            }

//			Long shddh;
//			shddh = Long.parseLong(notifyPayedPojo.getOutOrderNumber());
            Long mzxh = identityManager.getMax("MS_MZXX", 1);

            Date now = new Date();

            List<BillDataPojo> billList = notifyPayedPojo.getFeeRecords();
            Long jzxh = null;

            List<String> cfsbList = new ArrayList<>();  //处方列表
            List<String> yjxhList = new ArrayList<>();  //医技列表

            //获取单据列表 包含处方 医技
            for (BillDataPojo feeRecord : billList) {
                //feeTypeCode:1,西药，2中药，3草药
                if ("1".equals(feeRecord.getFeeTypeCode()) || "2".equals(feeRecord.getFeeTypeCode()) || "3".equals(feeRecord.getFeeTypeCode())) {
                    cfsbList.add(feeRecord.getFeeNo());

                    if (jzxh == null || jzxh < 1) {
                        jzxh = paymentMapper.getJzxhCF(Long.parseLong(feeRecord.getFeeNo()));
                    }
                } else {
                    yjxhList.add(feeRecord.getFeeNo());
                    if (jzxh == null || jzxh < 1) {
                        jzxh = paymentMapper.getJzxhYJ(Long.parseLong(feeRecord.getFeeNo()));
                    }

                }
            }

//			结算逻辑
//			1、执行预结算逻辑，获取支付金额
            GetPrecalculatedFeePojo getPrecalculatedFeePojo = new GetPrecalculatedFeePojo();

            getPrecalculatedFeePojo.setOrganizationId(notifyPayedPojo.getOrganizationId());
            getPrecalculatedFeePojo.setPatientId(notifyPayedPojo.getPatientId());
            getPrecalculatedFeePojo.setFeeRecords(notifyPayedPojo.getFeeRecords());

            BaseResponse<GetPrecalculatedFee> precalculatedResponse = getPrecalculatedFee(getPrecalculatedFeePojo, 1, true);
            logger.info("========== precalculatedResponse : {} ===========", precalculatedResponse);

            //判断预结算是否成功
            if ((precalculatedResponse.getCode() != Constant.successTag && precalculatedResponse.getCode() != Constant.successResponse) || precalculatedResponse.getData() == null) {
                logger.info("========= 预结算失败 =============");
                baseResponse.setCode(-1);
                baseResponse.setMessage("预结算失败");
                return baseResponse;
            }

            //预结算成功，准备结算
//            GetPrecalculatedFee data = precalculatedResponse.getData();
//            feeSettlement = data.getFeeSettlement();
//            FeeSettlementResponse settlementResponse = null;
//            if (feeSettlement != null) {
//                settlementResponse = ybService.feeSettlement(feeSettlement);
//                logger.info("======= 医保结算返回参数:{} ========", settlementResponse);
//                String zxjylsh = data.getZxjylsh();
//                String jylsh = data.getJylsh();
//                ybServiceMapper.updateYcjd(jylsh, zxjylsh, mzxh);
//                logger.info("======= Ycjd保存成功 ========");
//
//            } else {
//                logger.info("======= 医保结算失败 ========");
//                baseResponse.setCode(Constant.errorTag);
//                baseResponse.setMessage("医保结算处理失败");
//            }
//			if(1==1){
//				return baseResponse;	
//			}


//
            GetPrecalculatedFee precalculatedFee = new GetPrecalculatedFee();
            precalculatedFee = precalculatedResponse.getData();
//
            //判断预结算金额和传入金额是否相等
            if (new BigDecimal(notifyPayedPojo.getPayAmount() + "").compareTo(new BigDecimal(precalculatedFee.getPayAmount() + "")) != 0) {
                baseResponse.setCode(Constant.errorTag);
                baseResponse.setMessage("传入的付款金额【" + notifyPayedPojo.getPayAmount() + "】和单据实际金额不相等【" + precalculatedFee.getPayAmount() + "】");
                return baseResponse;
            }

//			2、获取发票号码等信息：

            String fphm = systemConfigMapper.getValueByConfigName(1L, "WX_FPHM");
            Long wx_fphm = Long.parseLong(fphm) + 1;
            systemConfigMapper.updateValueByConfigName(1L, "WX_FPHM", wx_fphm.toString());


//			4、读取帐户信息帐户
            PatientDomain patient = patientMapper.getPatientById(brid);


            Long dzfpbz = 0L;
            //判断是否启用电子发票
            String value = systemConfigMapper.getValueByConfigName(jgid, "WECHAT_INVOICE_ACTIVATION");
            if(StringUtils.isNotBlank(value)){
                dzfpbz = Long.parseLong(value);
            }

//			5、写门诊信息ms_mzxx
            MS_MZXXDomain mzxx = new MS_MZXXDomain();

            mzxx.setBrid(brid);
            mzxx.setFphm(fphm);
            mzxx.setJgid(jgid);
            mzxx.setMzxh(mzxh);
            mzxx.setSfrq(now);
            mzxx.setBrxm(patient.getBrxm());
            mzxx.setBrxb(patient.getBrxb());
            mzxx.setBrxz(1000L);
            mzxx.setFyzh(patient.getFyzh());
            mzxx.setDwxh(patient.getDwxh());
            mzxx.setJzrq(null);
            mzxx.setCzgh("900001");
            mzxx.setZfpb(0);
            mzxx.setThpb(0);
            mzxx.setHbbz(0);

            mzxx.setZjje(precalculatedFee.getTotalFee());
            mzxx.setZfje(precalculatedFee.getPayAmount());
            //0：真实发票 1：门诊虚拟发票 2：药房虚拟发票 3：医技虚拟发票 4：诊间结算 5：自助结算，此处建议新增6：掌上医院
            mzxx.setSffs(0);

            mzxx.setQtys(precalculatedFee.getTotalFee() - precalculatedFee.getPayAmount());

            RegisterDomain register = registerMapper.getRegisterByJzxh(jgid, jzxh);
            mzxx.setMzlb(register.getMzlb());
            mzxx.setGhgl(register.getSbxh());
            mzxx.setApplx(5L);
            //交易流水号
            mzxx.setAppzfdjh(notifyPayedPojo.getAgtOrderNumber());
            mzxx.setFphm(fphm);
            mzxx.setAppzfje(notifyPayedPojo.getPayAmount());
            mzxx.setAppzffs("1");

//            if(settlementResponse != null){
//                mzxx.setDjlsh(settlementResponse.getYwzqh());
//                mzxx.setFsfjylsh(settlementResponse.getYbjylsh());
//                mzxx.setZxjylsh(settlementResponse.getJylsh());
//            }
            mzxx.setDzfpbz(dzfpbz);
            paymentMapper.saveMZXX(mzxx);

//			3、插入ms_sfmx表
//			将取预结算中归并的费用集合sfxm中的sfxm/zjje/zfje，另外补充字段数据jgid，fphm，mzxh

            for (GetPrecalculatedFeeData precalculatedFeeData : precalculatedFee.getMergingItems()) {
                MS_SFMXDomain sfmx = new MS_SFMXDomain();
                sfmx.setFphm(fphm);
                sfmx.setJgid(jgid);
                sfmx.setMzxh(mzxh);
                sfmx.setSfxm(precalculatedFeeData.getMergingCode().longValue());
                sfmx.setZfje(precalculatedFeeData.getMergingSubtotal());
                sfmx.setZjje(precalculatedFeeData.getMergingSubtotal());
                paymentMapper.saveSFMX(sfmx);
            }

//			6、写ms_cf01、ms_yj01相关数据

            paymentMapper.updateCF(Long.parseLong(fphm), mzxh, jgid, cfsbList);
            paymentMapper.updateYJ(Long.parseLong(fphm), mzxh, jgid, cfsbList, yjxhList);

//			7、写付款信息
//			如果zfje>0,则新增记录insert ms_fkxx:
            Long jlxh;
            Long fkfs = null;
            Long fklb = null;
            Long brxz = null;

            if (precalculatedFee.getPayAmount() > 0) {
                MS_FKXXDomain fkxx = new MS_FKXXDomain();
                jlxh = identityManager.getMax("MS_FKXX", 1);
                fkxx.setJlxh(jlxh);
                fkxx.setFkfs(notifyPayedPojo.getPayMode().longValue());
                fkxx.setFkhm(notifyPayedPojo.getChannelOrderNumber());
                fkxx.setFkje(precalculatedFee.getPayAmount());
                fkxx.setJgid(jgid);
                fkxx.setMzxh(mzxh);
                fkxx.setAppfkfs("1");
                paymentMapper.saveFKXX(fkxx);
            }
////			如果qtys>0,则新增记录insert ms_fkxx:
//            if (precalculatedFee.getTotalFee() > precalculatedFee.getPayAmount()) {
//
//                MS_FKXXDomain fkxx = new MS_FKXXDomain();
//
////				获取其他应收对应的付款方式
//                String qybz = systemConfigMapper.getValueByConfigName(jgid, "MZ_QTYSXZ");
//                if (qybz != null && "1".equals(qybz)) {
//                    brxz = patient.getBrxz();
//                } else {
//                    fklb = (long) 14;
//                }
//
//                fkfs = paymentMapper.getQtysFkfs(jgid, fklb, brxz, (long) 1);
//                if (fkfs == null) {
//                    fkfs = (long) 0;
//                }
//                jlxh = identityManager.getMax("MS_FKXX", 1);
//                fkxx.setJlxh(jlxh);
//                fkxx.setFkfs(fkfs);
//                fkxx.setFkhm(notifyPayedPojo.getOutOrderNumber());
//                fkxx.setFkje(precalculatedFee.getPayAmount());
//                fkxx.setJgid(jgid);
//                fkxx.setMzxh(mzxh);
//                paymentMapper.saveFKXX(fkxx);
//            }

            //createOrderNoMapper.updateShddhYwzt(notifyPayedPojo.getOutOrderNumber(), 1, jgid.intValue());
            createOrderNoMapper.updateShddhZfzt(notifyPayedPojo.getPaymentBudgetNumber(), 1, new Date(), notifyPayedPojo.getPayMode(),
                    jgid.intValue(), notifyPayedPojo.getAgtOrderNumber(), fphm.toString());

//			如果dzje>0,则新增记录insert ms_fkxx:
//			Fkfs = #
//			其他字段同上
//			其中：获取打折对应的付款方式，付款类别为5的是打折优惠
//			SELECT FKFS  From GY_FKFS Where (JGID = # or JGID = 0 ) and 
//				FKLB = 5 And SYLX = 1
//
//			9、结算成功，返回数据。
            //notifyPayed.setTradeNo(mzxh.toString());
            notifyPayed.setResultId(mzxh.toString());
            notifyPayed.setInvoiceNumber(fphm.toString());
            notifyPayed.setAgtOrderNumber(notifyPayedPojo.getAgtOrderNumber());
            notifyPayed.setPaymentBudgetNumber(notifyPayedPojo.getPaymentBudgetNumber());

            List<NotifyPayedData> notifyPayedData = paymentMapper.getNotifyPayedData(jgid.toString(), cfsbList, yjxhList);
            ;

            notifyPayed.setFeeRecords(notifyPayedData);

//			baseResponse.setCode(Constant.successTag);
            baseResponse.setCode(Constant.successResponse);
            baseResponse.setMessage(notifyPayedPojo.getNotify());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            //业务流程任何异常都将调用撤销接口
//            boolean b = ybService.detailReportChancel(mzlsh, "", "900001", ybkh);
//            logger.info("========= 处方上传异常，撤销:{} =============", b);
//            boolean b1 = ybService.feeSettlementCancellation(feeSettlement);
//            logger.info("========= 结算失败，撤销:{} =============", b1);
//            e.printStackTrace();
//            baseResponse.setCode(Constant.errorTag);
//            baseResponse.setMessage("处理失败");
        }

        baseResponse.setData(notifyPayed);

        return baseResponse;
    }

}
